<?php

namespace AuctionCore\CarOwner;

use AuctionCore\AntNest\Sms;
use AuctionCore\System\AuctionException;
use \AuctionCore\Common\PhpMemcache;

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//

/**
 * 车主
 * @author       爱民
 */
class Owner
{

    private $model = null;
    private $owner_id = null;

    /**
     * 构造
     * @param    int $owner_id 车主id
     * @return   void
     */
    public function __construct($owner_id)
    {
        $this->owner_id = $owner_id;
        $this->model = M('car_owner');
    }

    /**
     * 开通车主登录网站
     * @param array info [用户名，密码,昵称,密保手机号,短信手机号]
     * @return user_id
     */
    public function enable_front_user($info)
    {
        if (is_numeric($info['user_name']) && (strlen($info['user_name']) == 11)) {
            $info['user_name'] = 'ou' . $info['user_name'];
        }
        $user_id = \AuctionCore\Account\FrontUser::create($info);
        $up_onwer_info = array();
        $up_onwer_info['uid'] = $user_id;
        $this->update($up_onwer_info);
        $fu = new \AuctionCore\Account\FrontUser($user_id);
        $fu->set_group(1); //帐号加车主组,组id为1
        return $user_id;
    }

    /**
     * 新增车主信息
     * 返回：车主id号
     * @param    array $info 车主信息
     * @return   int
     */
    public static function create($info)
    {
        //数据检验
        if (empty($info['seller_name'])) {
            AuctionException::make_throw('400001');
        }
        if (empty($info['phone'])) {
            AuctionException::make_throw('400002');
        }
        $id = M('car_owner')->add($info);
        // echo M()->getLastSql();
        return $id;
    }

    /*
     * //根据车主ID获取车源在流程中的状态(预约中、检测中、拍卖中、成交待确认、过户中、交易失败和交易成功)
     * 拍卖中-上拍审核通过；
     * 成交待确认-成交待确认；
     * 过户中-核实收款；
     * 交易成功-付完尾款；
     * 交易失败-各种流程失败
     * @param $owner_id   车主ID（即线索ID）                                                      5
     * */

    public static function get_car_status($owner_id)
    {
        //1,待预约检测 2,预约检测跟踪中 3,预约检测失败 4,待检测 5,检测成功 6,检测失败
        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $owner_detail = $owner->detail();
        switch ($owner_detail['business_status']) {
            case "1":
            case "2":
                $state = '预约中';
                break;
            case "4":
            case "5":
                $state = '检测中';
                break;
            case "3":
            case "6":
                return '交易失败';
                break;
            default:
                break;
        }
        //车源状态
        //车辆状态(1 待审核,2 审核失败,3 审核驳回,4 待拍卖,5 拍卖中,6 流拍,7 待重拍, 8 交易失败, 9 交易成功)
        $car = \AuctionCore\CarResource\Car::get_car_by_owner_id($owner_id);
        if ($car) {
            switch ($car['car_status']) {
                case "1":
                case "3":
                case "4":
                    $state = "检测中";
                    break;
                case "5":
                    $state = '拍卖中';
                    break;
                case "6":
                case "7":
                    $state = '待确认';
                    break;
                case "2":
                case "8":
                    return '交易失败';
                    break;
                case "9":
                    $state = '交易成功';
                    break;
                default:
                    break;
            }
            if ($car['car_status'] == 5) {
                //最新的拍单状态
                //拍单状态(1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5成效待确认,6拍单流拍,7待签约,8待付首款，801已付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功
                $order = \AuctionCore\AuctionOrder\AuOrder::get_order_by_car_id($car['car_id']);
                if ($order) {
                    switch ($order['status']) {
                        case "1":
                        case "2":
                            $state = '检测中';
                            break;
                        case "3":
                        case "301":
                        case "4":
                            $state = '拍卖中';
                            break;
                        case "7":
                        case "8":
                        case "801":
                        case "9":
                        case "10":
                        case "5":
                        case "6":
                        case "11":
                            $state = '待确认';
                            break;
                        case "12":
                            return '交易失败';
                            break;
                        case "13":
                            $state = '交易成功';
                            break;
                        default:
                            $state = '拍卖中';
                            break;
                    }
                    //该车历史单，有一个与车主签约则固定显示待确认状态
                    $s = \AuctionCore\AuctionOrder\AuOrder::get_signed_order($car['car_id']);
                    if ($s) {
                        $status = '待确认';
                    }
                }
            }
        }


        return $state;
    }

    /**
     * 新增合作伙伴车主信息
     * 返回：车主id号
     * @param    array $info 车主信息
     * @return  int
     */
    public static function create_partner_owner($info)
    {
        //数据检验
        if (empty($info['partner_id'])) {
            AuctionException::make_throw('1300001');
        }
        if (empty($info['owner_id'])) {
            AuctionException::make_throw('400004');
        }
        if (empty($info['car_no'])) {
            AuctionException::make_throw('700042');
        }
        $id = M('partner_owner')->add($info);
        return $id;
    }

    /**
     * 新增合作伙伴车主信息原始信息备份
     * 返回：车主id号
     * @param    array $info 车主信息
     * @return  int
     */
    public static function create_partner_owner_src($info)
    {
        $id = M('partner_owner_src')->add($info);
        return $id;
    }

    /**
     * 获取车商TOKEN KEY
     * @param $code
     */
    public static function get_partner($code)
    {
        $rs = M('partner')->where("code='" . $code . "'")->find();
        return $rs;
    }

    /**
     * 获取车合作伙伴车源信息
     * @param $car_no
     * @return array
     */
    public static function get_partner_car($car_no)
    {
        $cols = "c.car_status,c.mbrand_id,c.series_id,c.model_id,c.pointer_mileage,c.first_reg_date
                        ,o.bid_best_price,o.bidding_best_price,o.success_price,po.owner_id";

        $ret = M('partner_owner')->alias('po')->field($cols)->join(" LEFT JOIN " . C('DB_PREFIX') . "cars c ON po.owner_id=c.owner_id")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "order o ON o.car_id=c.car_id")->where("po.car_no='" . $car_no . "'")
            ->find();

        $car_info = array();
        if ($ret['car_status']) {
            //状态
            $car_info['status'] = self::car_status_for_partner($ret['owner_id']); //C('CAR_STATUS.' . $ret['car_status']);
            //成交价
            $best_price = $ret['bid_best_price'] > $ret['bidding_best_price'] ? $ret['bid_best_price'] : $ret['bidding_best_price'];
            $car_info['best_price'] = $best_price ? $best_price : '0.00';
            //实际成交价
            $car_info['success_price'] = $ret['success_price'];


            $car = new \AuctionCore\CarResource\CarModel();
            //品牌
            $brand = $car->get_model_by_id($ret['mbrand_id'], 'mbrand');
            $car_info['brand'] = $brand['name'];
            //车系
            $series = $car->get_model_by_id($ret['series_id'], 'series');
            $car_info['series'] = $series['name'];
            //车型
            $model = $car->get_model_by_id($ret['model_id']);
            $car_info['model'] = $model['name'];
            //表显里程
            $car_info['pointer_mileage'] = intval($ret['pointer_mileage']) . '万公里';
            //初登日期
            $car_info['first_reg_date'] = $ret['first_reg_date'];
        } else {
            $car_info['status'] = self::car_status_for_partner($ret['owner_id']);
        }
        return $car_info;
    }

    /*
     *
     * 车源合作伙伴看到的车源状态
     * @param $owner_id   车主ID（即线索ID）                                                      5
     * */

    public static function car_status_for_partner($owner_id)
    {
        //1,待预约检测 2,预约检测跟踪中 3,预约检测失败 4,待检测 5,检测成功 6,检测失败
        $owner = new \AuctionCore\CarOwner\Owner($owner_id);
        $owner_detail = $owner->detail();
        switch ($owner_detail['business_status']) {
            case "1":
                $state = '待处理';
                break;
            case "2":
                $state = '预约中';
                break;
            case "4":
            case "5":
                $state = '检测中';
                break;
            case "3":
            case "6":
                return '交易失败';
                break;
            default:
                $state = '信息重复';
                break;
        }
        //车源状态
        //车辆状态(0待上传协议,1 待审核,2 审核失败,3 审核驳回,4 待拍卖,5 拍卖中,6 流拍,7 待重拍, 8 交易失败, 9 交易成功)
        $car = \AuctionCore\CarResource\Car::get_car_by_owner_id($owner_id);
        if ($car) {
            switch ($car['car_status']) {
                case "1":
                case "3":
                case "4":
                    $state = "检测中";
                    break;
                case "5":
                    $state = '拍卖中';
                    break;
                case "6":
                case "7":
                    $state = '待确认';
                    break;
                case "2":
                case "8":
                    $state = '交易失败';
                    break;
                case "9":
                    $state = '交易成功';
                    break;
                default :
                    $state = "检测中";
                    break;
            }

            //拍单状态
            //拍单状态(1审核中,2审核驳回,3投标中,301等待竞标,4竟标中,5成效待确认,6拍单流拍,7待签约,8待付首款，801已付首款,9待过户,10过户中,11待付尾款,12拍单失败,13拍单成功
            $order = \AuctionCore\AuctionOrder\AuOrder::get_order_by_car_id($car['car_id']);
            if ($order) {
                switch ($order['status']) {
                    case "1":
                    case "2":
                        $state = '检测中';
                        break;
                    case "3":
                    case "301":
                    case "4":
                    case "7":
                    case "8":
                    case "801":
                    case "9":
                    case "10":
                    case "5":
                    case "6":
                        $state = '待确认';
                        break;
                    case "11":
                        $state = '过户中';
                        break;
                    case "12":
                        return '交易失败';
                        break;
                    case "13":
                        $state = '交易成功';
                        break;
                    default:
                        $state = '拍卖中';
                        break;
                }
            }
        }
        return $state;
    }

    /**
     * 更新合作合伙车源表信息
     * @param $po_id
     * @return bool
     */
    public function update_partner_owner($owner_id, $info)
    {
        $res = M('partner_owner')->where("owner_id='" . $owner_id . "'")->save($info);
        return $res;
    }

    /**
     * 更新合作合伙原始车源表信息
     * @param $pos_id
     * @return bool
     */
    public static function update_partner_owner_src($pos_id)
    {
        $data = array('result' => '1');
        $res = M('partner_owner_src')->where("pos_id='" . $pos_id . "'")->save($data);
        return $res;
    }

    /**
     * 判断车主是否已存在
     * @param $phone
     * @return mixed
     */
    public static function is_exists($phone)
    {
        $owner = M('car_owner')->where("phone='" . $phone . "'")->find();
        return $owner;
    }

    /**
     * //生成新的合伙伙伴车源编号
     * @param $partner_id
     * @return string
     */
    public static function get_next_car_no($partner_id)
    {
        $cdt = array('partner_id' => array('eq', $partner_id));
        $row = M('partner_owner')->where($cdt)->order('po_id DESC')->find();
        if ($row) {
            preg_match("/" . $partner_id . "C([\d]+)/", $row['car_no'], $matches);
            $no = $matches[1] + 1;
        } else {
            $no = '1';
        }
        return $partner_id . 'C' . $no;
    }

    //车主登录
    public static function login($user_name, $pwd)
    {
        /* if(is_numeric($user_name)&&(strlen($user_name)==11)){
          $user_name='ou'.$user_name;
          } */
        $front_user = new \AuctionCore\Account\FrontUser($user_name);
        $info = $front_user->check_pwd($pwd);
        if ($info) {
            //检查是否有车主中心权限
            $fu = new \AuctionCore\Account\FrontUser($info['user_name']);
            if (!$fu->check_auth("owner_center")) {
                AuctionException::make_throw('400003');
            }

            //更新互斥登录
            $ul = new \AuctionCore\Account\UniqLogin();
            $uniq_login_token = $ul->update($info['uid']);
            $info['uniq_login_token'] = $uniq_login_token;

            $owner = M('car_owner');
            $info['owner_info'] = $owner->where("uid='{$info['uid']}'")->find();
            unset($info['passwd']);
            unset($info['pwd_mobile']);
            unset($info['status']);
            return $info;
        }
        return false;
    }

    //不传密码，车主登录方式
    public static function loginByLoginKey($user_name, $login_key, $time)
    {
        try {
            $front_user = new \AuctionCore\Account\FrontUser($user_name);
            if (!$front_user->check_auth("owner_center")) {
                AuctionException::make_throw('400003');
            }
            $info = $front_user->user_info();

            if ($info['status']) {
                AuctionException::make_throw('200010');
            }

            $pwd_md5 = $info['passwd'];
            if ($info && $login_key == sha1($user_name . $info['passwd'] . $time . C('auth')['salt'])) {

                $mem = new PhpMemcache();
                if ($mem->get('appapi_login_' . $login_key) || (time() - ($time / 1000)) > 30) {
                    AuctionException::make_throw('100068');
                }

                //更新互斥登录
                $ul = new \AuctionCore\Account\UniqLogin();
                $uniq_login_token = $ul->update($info['uid']);
                $info['uniq_login_token'] = $uniq_login_token;

                unset($info['passwd']);
                unset($info['pwd_mobile']);
                unset($info['status']);

                //记录登录请求key
                $mem->set('appapi_login_' . $login_key, $user_name, 40);
                return array($info, $pwd_md5);
            } else {
                AuctionException::make_throw('200022');
            }
        } catch (AuctionException $e) {
            if ($e->getCode() == '200008') {
                AuctionException::make_throw('200022');
            }
            AuctionException::make_throw($e->getCode());
        }
    }

    /**
     * 删除车主信息
     * 返回：车主id号
     * @param    array $info 车主信息
     * @return   int
     */
    public static function remove($owner_id)
    {
        $where = "owner_id='{$owner_id}'";
        $ok = M('car_owner')->where($where)->delete();
        return $ok;
    }

    /**
     * 更新车主信息
     * @param array $info 车主信息
     * @return int
     */
    public function update($info)
    {
        $where = "owner_id='" . $this->owner_id . "'";
        $info['modify_time'] = date('Y-m-d H:i:s');
        $ok = $this->model->where($where)->save($info);
        return $ok;
    }

    /**
     * 车主详细
     */
    public function detail()
    {
        $where = "owner_id='" . $this->owner_id . "'";
        $detail = $this->model->where($where)->find();
        return $detail;
    }

    /**
     * 分配客服人员
     * @param employee_id 客服人员id
     * @return true/false
     */
    public function assgin_waiter($employee_id)
    {
        $owner_info = $this->detail();
        if (intval($owner_info['service_id']) > 0)
            return false; //已被其它客服人员处理
        $up_info = array('service_id' => $employee_id);
        $where = "owner_id='" . $this->owner_id . "' and service_id=0 ";
        $ok = $this->model->save($up_info);
        return intval($ok) > 0;
    }

    /**
     * 预约成功
     * 记录跟踪，并保存预约信息
     * @param    array $result_info 结果信息  array格式：[预约时间，服务方式，预约地址，预约备注,客服id,客服姓名]
     * $booking_sucess_info = array(
     *        'reserve_time'=>''
     *        ,'service_method'=>'1'
     *        ,'reserve_provinc'=>'1'//省
     *        ,'reserve_city'=>'1'  //城市编号
     *        ,'reserve_area'=>'1'  //地区编号
     *        ,'reserve_address'=>'北里58号' //详址
     *        ,'reserve_remark' =>'备注'
     *    );
     * @return   int/false
     */
    public function booking_sucess($booking_sucess_info)
    {
        $booking_sucess_info['business_status'] = 2; //预约成功
        $ok = $this->update($booking_sucess_info);
        if (intval($ok) > 0) {
            $booking_info = array(
                'owner_id' => $this->owner_id,
                'waiter_id' => $booking_sucess_info['service_id'],
                'name' => $booking_sucess_info['service_name'],
                'remark' => $booking_sucess_info['reserve_remark'],
                'type' => 1,
                'next_trace_time' => $booking_sucess_info['reserve_time']
            );
            $this->save_booking_log($booking_info);
        }
        return $ok;
    }

    /**
     * 保存预约结果到预约日志。
     * @param    array $booking_info 预约结果信息
     * @return   int/false
     */
    public static function save_booking_log($booking_info)
    {
        $re_reace = M('reserve_trace');
        $now = date("Y-m-d H:i:s", time());
        $booking_info['createtime'] = $now;
        $ok = $re_reace->add($booking_info);
        return $ok;
    }

    /**
     * 预约跟踪
     * @param    array $booking_info 结果信息  array格式：[waiter_id:客服员工编号，name:员工姓名，remark:备注，next_trace_time:下次预约时间]
     * @return   true/false
     */
    public function booking_trace($booking_info)
    {
        $ok = $this->update(array('next_trace_time' => $booking_info['next_trace_time']));
        if (intval($ok) > 0) {
            $booking_info['type'] = 3;
            $booking_info['owner_id'] = $this->owner_id;

            $ok = $this->save_booking_log($booking_info);
        }
        return $ok;
    }

    /**
     * 预约失败
     * @param    array $result_info 结果信息 array格式：[waiter_id:客服员工编号，name:员工姓名，remark:备注]
     * @return   true/false
     */
    public function booking_faild($booking_info)
    {
        $owner_info = array('business_status' => 3); //预约失败
        $ok = $this->update($owner_info);
        if (intval($ok) > 0) {
            $booking_info['type'] = 2;
            $booking_info['owner_id'] = $this->owner_id;

            $ok = $this->save_booking_log($booking_info);
        }
        return $ok;
    }

    /**
     * 保存预约结果 - 日志信息
     * @param array $reserve_info
     * @return type
     */
    public static function save_reserve_log($reserve_info)
    {
        $reserve_info['createtime'] = date("Y-m-d H:i:s", time());
        return M('reserve_trace')->add($reserve_info);
    }

    /**
     * 获得车主预约跟踪日志
     */
    public function get_reserve_log()
    {
        $condition['l.owner_id'] = $this->owner_id;
        $log_list = M('reserve_trace')->alias('l')->field('l.*,e.real_name')
            ->join(C('DB_PREFIX') . "employee e ON e.emp_id=l.emp_id")
            ->where($condition)->order("l.createtime desc")->select();

        return $log_list;
    }

    /**
     * 获得车主预约跟踪日志 单个状态
     */
    public function get_reserve_single_log($condition)
    {
        $reserve_log = M('reserve_trace')->where($condition)->order('type DESC,rt_id DESC')->limit(1)->select();
        return $reserve_log;
    }

    /**
     * 获得车主预约跟踪日志
     * @return   array
     */
    public function booking_log()
    {
        $re_treace = M('reserve_trace');
        $where = "owner_id='{$this->owner_id}'";
        $log_list = $re_treace->where($where)->select();
        return $log_list;
    }

    /**
     * 分配评估师
     * @param    int $checker_id 评估师id
     * @param    string $checker_name 评估师名称
     * @param    string $assgin_remark 分配评估师备注
     * @return   boot/false
     */
    public function assgin_checker($checker_id, $checker_name, $assgin_remark)
    {
        $owner_info = array('business_status' => 4); //待检测
        $owner_info['checker_name'] = $checker_name;
        $owner_info['checker_id'] = $checker_id;
        $owner_info['assgin_remark'] = $assgin_remark;
        $ok = $this->update($owner_info);
        if ($ok) {
            return true;
        } else {
            return false;
        }
    }

    /*
     * 根据车主获取拍单ID
     * @return int
     * */

    public function get_order_id_by_owner_id()
    {
        //根据owner_id 找到所有的拍单，
        //如果拍单状态都为流拍，则返回最后一次的拍单ID
        //如果拍单中有一次为成效待确定，刚返回成交待确定的拍单ID
        $sql = "SELECT o.order_id,o.status,o.fail_type FROM " . C('DB_PREFIX') . "order o
                    INNER JOIN " . C('DB_PREFIX') . "cars c ON c.car_id=o.car_id
                        WHERE c.owner_id='" . $this->owner_id . "' AND (o.status >='5' OR (o.status='12' AND o.fail_type in('2','3','4','5')))";
        $res = M()->query($sql);
        foreach ($res as $value) {
            if (in_array($value['fail_type'], array('2', '3', '4', '5'))) {//拍单曾经到过 成效待确认
                return $value['order_id'];
            }
        }
        return $value['order_id'];
    }

    /*
     * 车主确认跟踪记录
     * @param array $data 数据
     *
     * */

    public function confirm_trace_log($data = array())
    {
        if (empty($data['order_id'])) {
            AuctionException::make_throw('700027');
        }

        $data['owner_id'] = $this->owner_id;
        $data['createtime'] = date('Y-m-d H:i:s');
        return M('owner_confirm_log')->add($data);
    }

    /**
     * 确定 or 磋商备注
     */
    public function read_remark($data = array())
    {

        if (empty($data['order_id'])) {
            return false;
        }
        $map = [];
        $map['owner_id'] = $this->owner_id;

        if ($data['result'] > 0) {
            $map['result'] = intval($data['result']);
        }
        return M('owner_confirm_log')->field('result,remark')->where($map)->order('createtime desc')->find();
    }

    /**
     * 车辆检测调度分配跟踪日志
     * @param type $owner_id 车主ID
     * @param type $car_check_action_log 日志文本
     */
    public function add_car_check_trace_log($car_check_action_log)
    {
        $car_check_trace = M('car_check_trace_log');
        $condition['owner_id'] = $this->owner_id;
        $total = $car_check_trace->where($condition)->count();
        if ($total > 0) {
            $action_log = $car_check_action_log['createtime'] . "/t" . $car_check_action_log['car_trace_msg'] . '/t' . $car_check_action_log['employee'] . '/n/t';
            $car_check_trace_log['action_log'] = array('exp', "CONCAT(`action_log`,'$action_log')");
            $ok = $car_check_trace->where($condition)->save($car_check_trace_log);
            return $ok;
        }
        $car_check_trace_log['owner_id'] = $this->owner_id;
        $car_check_trace_log['action_log'] = $car_check_action_log['createtime'] . "/t" . $car_check_trace_log['car_trace_msg'] . '/t' . $car_check_trace_log['employee'] . '/n/t';
        $ok = $car_check_trace->add($car_check_trace_log);
        return $ok;
    }

    /**
     * 车来车往APP 预约卖车
     */
    public function create_booking_car($data, $isEvaluation = 0)
    {
        $data['posttime'] = date("Y-m-d H:i:s", time());
        $condition['co.phone'] = array('eq', $data['phone']);
        $condition['co.business_status'] = array('NOT IN', '3,6');
        $order = 'co.owner_id DESC';
        $res = $this->model->alias('co')->field('co.owner_id,c.car_id')
            ->join(" LEFT JOIN " . C('DB_PREFIX') . "cars as c ON co.owner_id=c.owner_id")
            ->where($condition)
            ->order($order)
            ->find();
        if (!empty($res['owner_id'])) {
            $condition['co.owner_id'] = array('eq', $res['owner_id']);
            if (!empty($res['car_id'])) {
                $condition['c.car_status'] = array('NOT IN', '2,8,9');
                $total = $this->model->alias('co')
                    ->join(" LEFT JOIN " . C('DB_PREFIX') . "cars as c ON co.owner_id=c.owner_id")
                    ->where($condition)
                    ->order($order)
                    ->count();
            } else {
                $total = $this->model->alias('co')
                    ->join(" LEFT JOIN " . C('DB_PREFIX') . "cars as c ON co.owner_id=c.owner_id")
                    ->where($condition)
                    ->order($order)
                    ->count();
            }
            if ($total > 0) {
                if ($isEvaluation == 1) {
                    AuctionException::make_throw('200078');
                }
                AuctionException::make_throw('200070');
            }
        }
        return M('car_owner')->add($data);
    }

    /**
     * 根据UID获取OWNER信息
     * @param $uid
     * @return mixed
     */
    public static function get_owner_by_uid($uid)
    {
        return M('car_owner')->where("uid='" . $uid . "'")->find();
    }

    /**
     * 根据电话号码获取OWNER信息
     * @param $uid
     * @return mixed
     */
    public static function get_owner_by_phone($phone)
    {
        return M('car_owner')->where("phone='" . $phone . "'")->order("owner_id DESC")->find();
    }

    /**
     * 根据owner的phone查询是否 存在车主帐号，存在则更新owner表uid，
     * 如不存在则创建车主帐号返回uid，更新owner表中uid
     */
    public function create_owner_user($owner_id, $phone)
    {
        $condition['pwd_mobile'] = $phone;
        $user = M('user')->where($condition)->find();
        $data = array();
        if (!empty($user)) {
            $data['owner_id'] = $owner_id;
            $data['uid'] = $user['uid'];
            //短信通知车主
            $sms = new Sms();
            $sms->notify(17, $phone, array());
        } else {
            $detail = $this->detail();
            $info['phone'] = $phone;
            $info['user_name'] = gen_rand_user_name('au');
            $info['passwd'] = md5('123456');
            $info['nick_name'] = $detail['seller_name'];
            $info['real_name'] = $detail['seller_name'];
            $info['sms_mobile'] = $phone;
            $info['pwd_mobile'] = $phone;
            $info['reg_from'] = 5;  //运营平台审核通过创建用户
            $user_id = \AuctionCore\Account\OwnerUser::create($info, true);
            $data['owner_id'] = $owner_id;
            $data['uid'] = $user_id;
            //如果创建用户A是B的客户，则创建帐号A是B的下级
            $myCustomer = new \AuctionCore\Other\MyCustomer();
            $customer = $myCustomer->getCustomer(['owner_id' => $owner_id, 'status' => '1']);
            if (!empty($customer)) {
                \AuctionCore\Broker\Broker::create($user_id, $customer['uid']);
            }
            //创建车主帐号，短信通知车主帐号密码
            $sms = new Sms();
            $sms->notify(16, $phone, array('mob' => $phone, 'pwd' => '123456'));
        }
        return M('car_owner')->save($data);
    }

    /**
     * 根据注册车来车往APP手机号，如果owner表有数据且我的客户表中在待验证状态则把注册uid关联到owner表中
     */
    public static function create_relation_owner_by_reg($phone, $uid = 0)
    {
        $condition['mc.phone'] = $phone;
        $condition['mc.status'] = 0;
        $customer_detail = M('my_customer')->alias("mc")->field('mc.owner_id')
            ->join(C('DB_PREFIX') . "car_owner co ON mc.`owner_id`=co.`owner_id`")
            ->where($condition)
            ->find();
        if (!empty($customer_detail['owner_id'])) {
            $data = array();
            $data['uid'] = $uid;
            $data['owner_id'] = $customer_detail['owner_id'];
            $res = M('car_owner')->save($data);
            if ($res === false) {
                \Think\Log::record("消息：客户关联到卖车用户uid失败,时间：" . date("Y-m-d H:i:s"));
            }
        }
    }

    /**
     * 获取预约验车地点
     *
     * @param $store_id  int
     * @param $owner_id  int
     *
     * @return mix
     */
    public static function get_reserve_address($store_id = '', $owner_id)
    {
        $addr = new \AuctionCore\Other\Address();
        $store = new \AuctionCore\Other\Store();
        $revAddress = '';
        if (!empty($store_id)) { // 回车类型
            $storeInfo = $store->detail(array('store_id' => $store_id));
            $revAddress = $storeInfo['store_name'];
        } else {
            $ownerObj = new \AuctionCore\CarOwner\Owner($owner_id);
            $ownerInfo = $ownerObj->detail();
            if ($ownerInfo['sign_service_method'] == 2) {
                // $province = $addr->get_name_by_code($ownerInfo['sign_reserve_province']);
                $city = $addr->get_name_by_code($ownerInfo['sign_reserve_city']);
                $area = $addr->get_name_by_code($ownerInfo['sign_reserve_area']);
                $revAddress = $city . $area . $ownerInfo['sign_reserve_address'];
            } elseif ($ownerInfo['sign_service_method'] == 3) {
                $address = $store->detail(array('store_id' => $ownerInfo['sign_reserve_store']));
                $revAddress = $address['store_name'];
            }
        }
        return $revAddress;
    }

}
